import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/pages/address_selector/address_model.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import '../../../helper.dart';
import '../../../router.dart';
import 'order_state.dart';

class OrderLogic extends GetxController {
  final OrderState state = OrderState();

  @override
  void onReady() {
    var condition = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "card_status": 3, //购物卡状态 (1: 有效, 2:失效, 3: 可用)
      'access_token': SpUtil.getString('token'),
    };
    Api.walletInformation(condition).listen((event) {
      print('===========walletInformation==========');
      print(event);
      /*
      * {code: 0, message: 成功, full_message: null, available_cards: [],
      * invalid_cards: null, available_cards: [], valid_card_count: 0, total_card_count: 0,
      * invalid_card_count: null, total_available_amount: 0.0}
      *
      * */
      if (event['code'] == 0) {
        state.GiftcardList = event['available_cards'] ?? [];
        if (state.GiftcardList.length > 0) {
          for (var i = 0; i < state.GiftcardList.length; i++) {
            state.GiftcardList[i]['click'] = false;
          }
        }
      }
      update();
    });
  }

  void goToMoney(id) {
    var params1 = {
      'access_token': SpUtil.getString('token'),
      "out_trade_no": id,
      "plat_type": 7,
      "body": "jifen",
      "pay_way": 0,
      "use_platform": 2,
      'appid': Config.ZJ_APPID,
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'),
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };

    gotomoney(state, startCPCNWeixinPay, params1, id);
  }

  /// 拉起中金支付
  void startCPCNWeixinPay(String authCode) async {
    print('authCode ==========> $authCode');
    if (authCode.isEmpty) {
      return;
    }

    var result =
        await fluwx.payWithCPCN(appId: Config.WECHAT_APPID, authCode: authCode);

    // var result = fluwx.openWeChatApp();

    print("=========结果<<<$result>>>====");
  }

  void setGift(index) {
    print(state.isGiftMoney);
    setcard(state, index);
    update();
  }

  // add by gyq
  //通过状态获取下标
  int getTabIndex() {
    int index = 0;
    int orderstatus = state.orderStatus;
    print('_getTabIndex===');
    print(orderstatus);
    switch (orderstatus) {
      case 1:
        index = 1;
        break;
      case 2:
        index = 2;
        break;
      case 3:
        index = 3;
        break;
      case 4:
        index = 4;
        break;
      case 17:
        index = 5;
        break;
    }
    return index;
  }

  //通过下标获取状态
  void upgradeStateOrderStatus() {
    switch (state.index) {
      case 0:
        state.orderStatus = 0;
        break;
      case 1:
        state.orderStatus = 1;
        break;
      case 2:
        state.orderStatus = 2;
        break;
      case 3:
        state.orderStatus = 3;
        break;
      case 4:
        state.orderStatus = 4;
        break;
      case 5:
        state.orderStatus = 17;
        break;
    }
  }

  void getOrderInfoList({
    List list,
    int index,
  }) {
    if (index != null) {
      state.OrderInfoList[index] = list;
    } else {
      state.OrderInfoList = list;
    }
    update();
  }

  void searchOrderList({
    int index,
    int getOrderState,
  }) {
    String searchText = state.searchTextEditingController.text.trim();
    var params = {
      "client_type": 1,
      "page": 1,
      "page_size": 10,
      "order_status": getOrderState,
      "access_token": SpUtil.getString('token'),
      "key_word": searchText,
      "channel_num_id": 99,
      "use_platform": 2,
    };
    // if (searchText == '') {
    //   showToast('没有输入内容！');
    //   return;
    // }
    Api.searchOrderList(params).listen((event) {
      // if (event['orders'] != null && event['orders'].length > 0) {
      //   getOrderInfoList(list: event['orders'], index: index);
      // } else {
      //   getOrderInfoList(list: [], index: index);
      // }
      if (event['order_list_page'] != null &&
          event['order_list_page']['content'] != null &&
          event['order_list_page']['content'].length > 0) {
        getOrderInfoList(
            list: event['order_list_page']['content'], index: index);
        state.page = 2;
        state.refreshControllerList[index].refreshCompleted();
        state.refreshControllerList[index].loadComplete();
      } else {
        getOrderInfoList(list: [], index: index);
        state.page = 1;
        state.refreshControllerList[index].refreshCompleted();
        state.refreshControllerList[index].loadNoData();
      }
    });
  }

  /// 退预售定金
  void refund({info}) {
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "evidence_list": [],
      "items": [
        {
          "item_num_id": info['item_details'][0]['item_num_id'],
          "qty": info['item_details'][0]['qty'],
          "price": info['item_details'][0]['trade_price'],
          "pmt_sign": info['item_details'][0]['pmt_sign'],
          // "tml_line": info['item_details'][0]['tml_line']
          "tml_line": info['item_details'][0]['series']
        }
      ],
      "remark": 1,
      "return_type": 1,
      "source_tml_num_id": info['order_num_id'],
      "access_token": SpUtil.getString('token'),
      "all_refund": 1,
      "return_way": 1,
      "goodsReturn_flag": 0
    };

    Api.tkApply(params).listen((event) {
      if (event['code'] == 0) {
        toast(event['message']);
        Navigator.pop(Get.context);
        Get.toNamed(RouteConfig.applySuccess,
            arguments: {'back_tml_num_id': event['back_tml_num_id']});
      } else {
        toast(event['message']);
      }
      update();
    });
  }

  /// 加入购物车 老逻辑
  void buyAgain(Map info, int shopId) {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": 1.0,
      "ec_shop_num_id": shopId,
      "item_num_id": info['item_num_id'],
      "style_num_id": info['style_num_id'],
      "ec_style_num_id": info['style_num_id'],
      'access_token': SpUtil.getString('token'),
    };
    // var params = {
    //   "channel_num_id": 99,
    //   "use_platform": 2,
    //   "tenant_num_id": 6,
    //   "message_series": null,
    //   "request_num_id": null,
    //   "check_repeat_sign": null,
    //   "expose_method": null,
    //   "tml_num_id": info['order_num_id'],
    //   // "prv_num_id": "440000",
    //   // "city_num_id": "440300",
    //   // "city_area_num_id": "440307",
    //   "access_token": SpUtil.getString('token'),
    //   "usr_num_id": SpUtil.getInt('empeNumId')
    // };
    // Api.buyAgain(params).listen((event) {
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        // MainAppLogics.getCartNum();
        toast('添加成功');
      } else {
        toast('添加失败');
      }
    });
  }

  /// 加入购物车 修改后
  void buyAgain2(String order_num_id) {
    getCurrentLocationInfo(success: (data){
      var addressInfo = data['addressInfo'];
      var params = {
        "tenant_num_id": 6,
        "data_sign": 1,
        "message_series": null,
        "request_num_id": null,
        "check_repeat_sign": null,
        "expose_method": null,
        // "shop_id": shopId,
        "tml_num_id": order_num_id,
        "prv_num_id": '440000',
        "city_num_id": '440300',
        "city_area_num_id": '440307',
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        "access_token": SpUtil.getString('token'),
        "usr_num_id": SpUtil.getInt('empeNumId')
      };
      Api.buyAgain(params).listen((event) {
        print("===加入购物车===$event");
        if (event['code'] == 0) {
          toast('添加成功');
        } else {
          toast('添加失败');
        }
      });
    });
  }
}
